package com.yl.drug_management.service.impl;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.ruoyi.common.core.rabbitmq.RabbitMQ;
import com.ruoyi.common.core.rabbitmq.TestMQ;
import com.ruoyi.common.core.text.UUID;
import com.ruoyi.common.core.utils.StringUtils;
import com.yl.drug_management.service.TestMQService;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.nio.charset.StandardCharsets;

@Service
public class TestMQServiceImpl implements TestMQService {
    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Autowired
    private ObjectMapper mapper;

    @Override
    public boolean rabbitMqSend() {
        // 发送消息到队列
        //第一个参数交换机，第二个参数路由key，第三个参数需要发送的消息，第四个参数CorrelationData消息唯一编号
        //真正使用过程中可以根据需求将发送消息的代码封装进Util模块内
        MessageProperties messageProperties = new MessageProperties();
        messageProperties.setType("application/json");
        String json;

        try {
            json = mapper.writeValueAsString(new TestMQ().setMsg("发送消息"));
        } catch (Exception e) {
            throw new IllegalArgumentException("json 序列化异常");
        }
        //设置 messageId
        if (StringUtils.isEmpty(messageProperties.getMessageId())) {
            messageProperties.setMessageId(UUID.randomUUID().toString().replace("-", ""));
        }
        if (StringUtils.isEmpty(messageProperties.getCorrelationId())) {
            // 设置 关联 id
            messageProperties.setCorrelationId(UUID.randomUUID().toString().replace("-", ""));
        }
        Message message = new Message(json.getBytes(StandardCharsets.UTF_8), messageProperties);
        rabbitTemplate.convertAndSend(RabbitMQ.SERVICE_ONE_EXCHANGE, RabbitMQ.TEST_KEY_ROUTER, message,
                new CorrelationData(messageProperties.getCorrelationId()));
        return true;
    }
}
